package top.lingkang.securityoauth2.server.auth.impl;

import top.lingkang.securityoauth2.core.entity.ClientDetail;
import top.lingkang.securityoauth2.core.entity.DefaultClientDetail;
import top.lingkang.securityoauth2.server.auth.ClientDetailService;
import top.lingkang.securityoauth2.server.error.Oauth2ServerException;

import java.util.Arrays;
import java.util.List;

/**
 * @author lingkang
 * Created by 2022/8/2
 * 使用内存存储客户端信息
 */
public class InMemoryClientDetailService implements ClientDetailService {
    private String clientId;
    private String clientSecret;
    private List<String> grantType;

    public InMemoryClientDetailService() {
    }

    public InMemoryClientDetailService(String clientId) {
        this.clientId = clientId;
    }

    public InMemoryClientDetailService setClientId(String clientId) {
        this.clientId = clientId;
        return this;
    }

    public InMemoryClientDetailService setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
        return this;
    }

    public InMemoryClientDetailService setGrantType(String... grantType) {
        this.grantType = Arrays.asList(grantType);
        return this;
    }

    @Override
    public ClientDetail getClientDetail(String client_id, String client_secret, String grant_type) {
        if (!client_id.equals(clientId))
            throw new Oauth2ServerException("不存在的client_id: " + client_id);
        if (!grantType.contains(grant_type))
            throw new Oauth2ServerException("grant_type错误，应该为 password，当前: " + grant_type);
        if (!client_secret.equals(clientSecret))
            throw new Oauth2ServerException("client_secret错误");
        return new DefaultClientDetail("client_id", "client_secret", grantType.toArray(new String[]{}));
    }
}
